﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Wcs;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace DFGK.Service
{
    public class ReceivingOrderDetailService : BaseService, IReceivingOrderDetailService
    {
        private readonly IReceivingOrderDetailRepository _receivingOrderDetailRepository;
        private readonly IReceivingBillDetailRepository _receivingBillDetailRepository;
        private readonly IPutawayOrderDetailRepository _putawayOrderDetailRepository;
        private readonly IShippingLockCellRepository _shippingLockCellRepository;
        private readonly WcsHttpClient wcsHttp;
        private readonly IStackingStorageRepository _stackingStorageRepository;
        private readonly IInventoryDetailRepository _inventoryDetailRepository;
        private readonly IReceivingBillRepository _receivingBillRepository;
        private readonly IPutawayOrderRepository _putawayOrderRepository;
        private readonly IInventoryLogRepository _inventoryLogRepository;
        private readonly IWarehouseRepository _warehouseRepository;
        private readonly IInventoryRepository _inventoryRepository;
        private readonly IRoutewayRepository _routewayRepository;
        private readonly IInstructRepository _instructRepository;
        private readonly IMaterialRepository _materialRepository;
        private readonly IStationRepository _stationRepository;
        private readonly IPalletRepository _palletRepository;
        private readonly IShelfRepository _shelfRepository;
        private readonly ICellRepository _cellRepository;
        private readonly IAreaRepository _areaRepository;
        private readonly IEPCRepository _epcRepositroy;
        private readonly IUnitOfWork _unitOfWork;
        public ReceivingOrderDetailService(IMapper mapper, IReceivingBillRepository _receivingBillRepository, IReceivingOrderDetailRepository _receivingOrderDetailRepository, IReceivingBillDetailRepository _receivingBillDetailRepository, IPalletRepository _palletRepository, IUnitOfWork _unitOfWork, IStationRepository stationRepository, IStackingStorageRepository _stackingStorageRepository, IWarehouseRepository warehouseRepository, IAreaRepository areaRepository, IRoutewayRepository routewayRepository, IShelfRepository shelfRepository, ICellRepository cellRepository, IInventoryRepository inventoryRepository, IInstructRepository _instructRepository, IPutawayOrderRepository putawayOrderRepository, IPutawayOrderDetailRepository putawayOrderDetailRepository, IInventoryDetailRepository inventoryDetailRepository, IInventoryLogRepository inventoryLogRepository, IMaterialRepository materialRepository, IShippingLockCellRepository shippingLockCellRepository, WcsHttpClient wcsHttp, IEPCRepository epcRepositroy) : base(mapper)
        {
            this._receivingOrderDetailRepository = _receivingOrderDetailRepository;
            this._receivingBillDetailRepository = _receivingBillDetailRepository;
            this._stackingStorageRepository = _stackingStorageRepository;
            this._receivingBillRepository = _receivingBillRepository;
            this._instructRepository = _instructRepository;
            this._palletRepository = _palletRepository;
            this._unitOfWork = _unitOfWork;
            _putawayOrderDetailRepository = putawayOrderDetailRepository;
            _shippingLockCellRepository = shippingLockCellRepository;
            this.wcsHttp = wcsHttp;
            _inventoryDetailRepository = inventoryDetailRepository;
            _putawayOrderRepository = putawayOrderRepository;
            _inventoryLogRepository = inventoryLogRepository;
            _inventoryRepository = inventoryRepository;
            _warehouseRepository = warehouseRepository;
            _materialRepository = materialRepository;
            _routewayRepository = routewayRepository;
            _stationRepository = stationRepository;
            _shelfRepository = shelfRepository;
            _areaRepository = areaRepository;
            _cellRepository = cellRepository;
            _epcRepositroy = epcRepositroy;
        }

        public bool AddReceivingOrderDetail(ReceivingBillOrderDto m, out string message)
        {
            message = "";
            string palletBarcode = "";
            decimal receivedQty = 0;
            var receivingBills = _receivingBillRepository.QueryEntityById(m.Id);
            if (receivingBills == null)
            {
                message = "收货单不存在";
                return false;
            }
            var receivingBillDetails = _receivingBillDetailRepository.QueryEntityWhere(x => x.BillId == receivingBills.Id);
            if (receivingBillDetails == null)
            {
                message = "收货单明细";
                return false;
            }
            //手动选择仓位
            if (!string.IsNullOrEmpty(m.StoLocation))
            {
                receivingBillDetails.StoLocation = m.StoLocation;
                var inventoryobj = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == m.StoLocation);
                if (inventoryobj != null)
                {
                    message = "该储位已被占用了！" + m.StoLocation;
                    return false;
                }
                #region 如果浅深位有货物产生移库操作
                //排
                string rows = m.StoLocation.Substring(0, 2);
                //列
                string columns = m.StoLocation.Substring(2, 2);
                if (string.IsNullOrEmpty(rows))
                {
                    message = "获取仓位排失败！";
                    return false;
                }
                if (string.IsNullOrEmpty(columns))
                {
                    message = "获取仓位列失败！";
                    return false;
                }
                int row = Convert.ToInt32(rows);
                int col = Convert.ToInt32(columns);
                //双深位：1列所有，16排5列，20排5列，21排5列，22排5列，8列所有
                //三深位：22排6列，23排9列，24排9列，25排9列                 
                if (col == 1)
                {
                    string modifiedcellcode = m.StoLocation.Substring(0, 2) + "02" + m.StoLocation.Substring(4);
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                    {
                        message = $"浅货位 {inventorycell.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }
                }
                else if (col == 6)
                {
                    string modifiedcellcode = m.StoLocation.Substring(0, 2) + "04" + m.StoLocation.Substring(4);
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                    {
                        message = $"浅货位 {inventorycell.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }
                    modifiedcellcode = m.StoLocation.Substring(0, 2) + "05" + m.StoLocation.Substring(4);
                    var inventorycellcode2 = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycellcode2 != null)
                    {
                        message = $"浅货位 {inventorycellcode2.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }
                }
                else if (col == 8)
                {
                    string modifiedcellcode = m.StoLocation.Substring(0, 2) + "07" + m.StoLocation.Substring(4);
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                    {
                        message = $"浅货位 {inventorycell.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }
                }
                else if (col == 9)
                {
                    string modifiedcellcode = m.StoLocation.Substring(0, 2) + "07" + m.StoLocation.Substring(4);
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                    {
                        message = $"浅货位 {inventorycell.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }
                    modifiedcellcode = m.StoLocation.Substring(0, 2) + "08" + m.StoLocation.Substring(4);
                    var inventorycell2 = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell2 != null)
                    {
                        message = $"浅货位 {inventorycell2.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }
                }
                else if (col == 5 && (row == 16 || row == 20 || row == 21 || row == 22))
                {
                    string modifiedcellcode = m.StoLocation.Substring(0, 2) + "04" + m.StoLocation.Substring(4);
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                    {
                        message = $"浅货位 {inventorycell.LocationCode} 被占用请先移走再进行该仓位入库！";
                        return false;
                    }

                }
                #endregion
            }
            receivingBillDetails.AreaId = m.AId;
            receivingBillDetails.Layer = m.Layer;
            receivingBillDetails.IsPick = m.IsPick;
            _unitOfWork.BeginTransaction();
            try
            {
                if (m.ReceivedQty <= 0)
                {
                    message = "收货数量不能小于0";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (m.ReceivedQty % 1 != 0)
                {
                    message = "收货数量包含小数";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (string.IsNullOrEmpty(m.PalletBarcode))
                {
                    message = "托盘为空";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (m.ReceivedQty > (receivingBillDetails.Qty - receivingBillDetails.ReceivedQty))
                {
                    message = "收货数量不能大于物料数量";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                else
                {
                    receivingBillDetails.ReceivedQty += m.ReceivedQty;
                }
                _receivingBillDetailRepository.UpdEntity(receivingBillDetails);
                palletBarcode = m.PalletBarcode;
                receivedQty = m.ReceivedQty;
                var palletbarobj = _palletRepository.QueryIsEntityWhere(x => x.PalletBarcode == palletBarcode);
                if (palletbarobj == null || palletbarobj.Status == 0)
                {
                    message = "未查询到此托盘" + palletBarcode;
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                bool reresult = false;
                if (receivingBillDetails.ReceivedQty == receivingBills.TotalQty)
                {
                    //全部收货完成
                    reresult = AddReceivingOrderDetail(receivingBillDetails, receivedQty, m.NowUserId, m.NowUserName, palletBarcode, out message);
                    if (!reresult)
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    receivingBills.Status = 2;
                    receivingBills.EndDate = DateTime.Now;
                    _receivingBillRepository.UpdEntity(receivingBills);
                }
                else
                {
                    reresult = AddReceivingOrderDetail(receivingBillDetails, receivedQty, m.NowUserId, m.NowUserName, palletBarcode, out message);
                    if (!reresult)
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    receivingBills.Status = 1;
                    _receivingBillRepository.UpdEntity(receivingBills);
                }
                if (_unitOfWork.SaveChangesEntity())
                {
                    StartInventoryDTO startInventoryDTO = new StartInventoryDTO();
                    startInventoryDTO.PalletCode = palletBarcode;
                    startInventoryDTO.ActualLocation = message;
                    startInventoryDTO.NowUserId = m.NowUserId;
                    startInventoryDTO.NowUserName = m.NowUserName;
                    reresult = StartReceivingOrderDetails(startInventoryDTO, out message);
                    if (reresult)
                    {
                        //生产环境不调用接口
                        //if (Config.IsDev == false)
                        //{
                        //    var wcsApiRes = wcsHttp.ModeSwitchInApi();//切换入库模式
                        //    if (wcsApiRes.Code != 0)
                        //    {
                        //        message = wcsApiRes.Msg;
                        //        _unitOfWork.RollbackChanges();
                        //        return false;
                        //    }
                        //}
                        message = startInventoryDTO.ActualLocation;
                        _unitOfWork.CommitChanges();
                        return true;
                    }
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }


        #region PDA
        /// <summary>
        /// 弃用开始入库，和收货入库合并成一步
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool StartReceivingOrderDetail(StartInventoryDTO m, out string message)
        {
            message = string.Empty;
            var stackingstoragelist = _stackingStorageRepository.GetEntityWhereAll(x => x.PalletBarcode == m.PalletCode).ToList();
            if (!stackingstoragelist.Any())
            {
                message = "找不到组垛信息";
                return false;
            }
            bool result = false;
            _unitOfWork.BeginTransaction();
            try
            {
                foreach (var item in stackingstoragelist)
                {
                    if (item.RelatedOrderDetailId == null || item.RelatedOrderDetailId < -0)
                    {
                        message = "入库信息有误！";
                        return false;
                    }
                    var reorderDetail = _receivingOrderDetailRepository.QueryEntityById((long)item.RelatedOrderDetailId); ;
                    if (reorderDetail == null)
                    {
                        message = "入库信息有误！";
                        return false;
                    }
                    if (reorderDetail.Status == 2)
                    {
                        message = "当前入库单正在作业中！";
                        return false;
                    }
                    if (reorderDetail.Status == 3)
                    {
                        message = "当前入库单已完成！";
                        return false;
                    }
                    var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == item.PalletBarcode);
                    if (pallobj == null || pallobj.Status == 0)
                    {
                        message = "该托盘已被禁用";
                        return false;
                    }
                    item.ActualLocation = m.ActualLocation;
                    _stackingStorageRepository.UpdEntity(item);
                    //组垛id
                    long? stackingStorageId = item.Id;
                    if (stackingStorageId == null || stackingStorageId <= 0)
                    {
                        message = "组垛信息有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    reorderDetail.Status = 2;
                    //添加指令
                    Instruct instruct = new Instruct
                    {
                        Status = 2,
                        WarehouseCode = reorderDetail.WarehouseCode,
                        ToLocation = m.ActualLocation,
                        StackingStorageId = stackingStorageId,
                        WorkDeviceType = 1,
                        InstructType = 1,
                        Action = 0,
                        RelatedOrderId = reorderDetail.Id,
                        DeviceCode = "",
                        ExpectedToLocation = m.ActualLocation,
                        InstructIndex = 1,
                        PalletBarcode = m.PalletCode,
                        Priority = 9999,
                        Qty = (decimal)reorderDetail.StackedQty,
                        BusinessType = (int)EmBusinessType.In,
                        CreateUserId = m.NowUserId,
                        CreateUserName = m.NowUserName,
                    };
                    _instructRepository.AddEntity(instruct);
                    var allocateCell = _cellRepository.QueryEntityWhere(x => x.Code == m.ActualLocation);
                    if (allocateCell == null)
                    {
                        message = "仓位信息有误！";
                        return false;
                    }
                    pallobj.LocationCode = allocateCell.Code;
                    pallobj.LocationName = allocateCell.Name;
                    _palletRepository.UpdEntity(pallobj);
                    //保存库存
                    Inventory inventory = new Inventory()
                    {
                        WarehouseId = allocateCell.WhId,
                        WarehouseCode = allocateCell.WhCode,
                        WarehouseName = allocateCell.WhName,
                        AreaCode = allocateCell.AreaCode,
                        AreaName = allocateCell.AreaName,
                        AreaId = allocateCell.AreaId,
                        LocationId = allocateCell.Id,
                        LocationCode = allocateCell.Code,
                        LocationDepth = allocateCell.DepthIndex,
                        LocationName = allocateCell.Name,
                        Status = 3,
                        PalletBarcode = m.PalletCode,
                        ParentPalletBarcode = item.PalletBarcode,
                        RelatedOrderDetailId = reorderDetail.Id,
                        BillType = (int)reorderDetail.BillType.GetValueOrDefault(),
                        IsLock = true,
                        MaterialId = reorderDetail.MaterialId,
                        MaterialCode = reorderDetail.MaterialCode,
                        MaterialName = reorderDetail.MaterialName,
                        CustomerId = reorderDetail.CustomerId,
                        CustomerName = reorderDetail.CustomerName,
                        SupplierId = reorderDetail.SupplierId,
                        SupplierName = reorderDetail.SupplierName,
                        HasSkuDetail = true,
                        PutawayQty = reorderDetail.Qty,
                        UnitId = reorderDetail.UnitId,
                        UnitName = reorderDetail.UnitName,
                        MaterialKeyId = reorderDetail.MaterialKeyId,
                        BatchNo = reorderDetail.BatchNo,
                        ExpireDate = reorderDetail.ExpireDate,
                        ProductDate = reorderDetail.ProductDate,
                        MaterialTypeCode = reorderDetail.MaterialTypeCode,
                        MaterialTypeName = reorderDetail.MaterialTypeName,
                        PickedQty = 0,
                        ErplocationCode = allocateCell.Erpcode,
                        RoutewayId = allocateCell.RoutewayId,
                        StackingStorageId = stackingStorageId,
                        LocationHeightType = allocateCell.HeightType,
                        LogicalPartCode = reorderDetail.LogicalPartCode,//按单据来
                        LocationColumnNo = allocateCell.ColumnNo,
                        LocationLayerNo = allocateCell.LayerNo,
                        LocationDistanceValue = allocateCell.DistanceValue,
                        LocationLineNo = allocateCell.LineNo,
                        AvailableQty = reorderDetail.ReceivedQty,
                        AllocateQty = 0,
                        CreateUserId = m.NowUserId,
                        CreateUserName = m.NowUserName,
                    };
                    _inventoryRepository.AddEntity(inventory);
                    if (!_unitOfWork.SaveChangesEntity())
                    {
                        message = "保存库存失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //库存明细保存
                    InventoryDetail inventoryDetail = new InventoryDetail()
                    {
                        Id = YitIdHelper.NextId(),
                        InventoryId = inventory.Id,
                        PalletBarcode = m.PalletCode,
                        SkuNum = reorderDetail.Qty,
                        IsSku = false,
                    };
                    _inventoryDetailRepository.AddEntity(inventoryDetail);
                    //保存上架单主表
                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string putawayCode = "PUT" + str;
                    PutawayOrder putawayOrder = new PutawayOrder();
                    putawayOrder.Id = YitIdHelper.NextId();
                    putawayOrder.Code = putawayCode;
                    putawayOrder.BillType = 1;
                    putawayOrder.RelatedOrderDetailId = reorderDetail.Id;
                    putawayOrder.StackingStorageId = (long)stackingStorageId;
                    putawayOrder.PalletBarcode = m.PalletCode;
                    putawayOrder.LocationCode = allocateCell.Code;
                    putawayOrder.LocationDepth = allocateCell.DepthIndex == 0 ? null : allocateCell.DepthIndex;
                    putawayOrder.Status = 4;
                    putawayOrder.Qty = reorderDetail.ReceivedQty;
                    putawayOrder.MaterialId = reorderDetail.MaterialId;
                    putawayOrder.MaterialCode = reorderDetail.MaterialCode;
                    putawayOrder.MaterialName = reorderDetail.MaterialName;
                    putawayOrder.MaterialKeyId = reorderDetail.MaterialKeyId;
                    putawayOrder.SourceType = 1;
                    putawayOrder.Roadway = allocateCell.RoutewayId.ToString();
                    putawayOrder.CreateUserName = m.NowUserName;

                    _putawayOrderRepository.AddEntity(putawayOrder);
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "保存库存失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //上架单明细表保存
                    PutawayOrderDetail putawayOrderDetail = new PutawayOrderDetail()
                    {
                        Id = YitIdHelper.NextId(),
                        PutawayOrderId = putawayOrder.Id,
                        PalletBarcode = m.PalletCode,
                    };
                    _putawayOrderDetailRepository.AddEntity(putawayOrderDetail);


                }
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }
        private bool StartReceivingOrderDetails(StartInventoryDTO m, out string message)
        {
            message = string.Empty;
            var stackingstoragelist = _stackingStorageRepository.GetEntityWhereAll(x => x.PalletBarcode == m.PalletCode && x.Status == 1).ToList();
            if (!stackingstoragelist.Any())
            {
                message = "找不到组垛信息";
                return false;
            }
            bool result = false;
            foreach (var item in stackingstoragelist)
            {
                if (item.RelatedOrderDetailId == null || item.RelatedOrderDetailId < -0)
                {
                    message = "入库信息有误！";
                    return false;
                }
                var reorderDetail = _receivingOrderDetailRepository.QueryEntityById((long)item.RelatedOrderDetailId);
                if (reorderDetail == null)
                {
                    message = "入库信息有误！";
                    return false;
                }
                if (reorderDetail.Status == 2)
                {
                    message = "当前入库单正在作业中！";
                    return false;
                }
                if (reorderDetail.Status == 3)
                {
                    message = "当前入库单已完成！";
                    return false;
                }
                var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == item.PalletBarcode);
                if (pallobj == null || pallobj.Status == 0)
                {
                    message = "该托盘已被禁用";
                    return false;
                }
                item.Status = 0;
                item.ActualLocation = m.ActualLocation;
                _stackingStorageRepository.UpdEntity(item);
                //组垛id
                long? stackingStorageId = item.Id;
                if (stackingStorageId == null || stackingStorageId <= 0)
                {
                    message = "组垛信息有误！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                reorderDetail.Status = 2;
                //添加指令
                Instruct instruct = new Instruct
                {
                    Status = 2,
                    WarehouseCode = reorderDetail.WarehouseCode,
                    ToLocation = m.ActualLocation,
                    StackingStorageId = stackingStorageId,
                    WorkDeviceType = 1,
                    InstructType = 1,
                    Action = 0,
                    RelatedOrderId = reorderDetail.Id,
                    DeviceCode = "",
                    ExpectedToLocation = m.ActualLocation,
                    InstructIndex = 1,
                    PalletBarcode = m.PalletCode,
                    Priority = 9999,
                    Qty = (decimal)reorderDetail.StackedQty,
                    BusinessType = (int)EmBusinessType.In,
                    CreateUserId = m.NowUserId,
                    CreateUserName = m.NowUserName,
                };
                _instructRepository.AddEntity(instruct);
                var allocateCell = _cellRepository.QueryEntityWhere(x => x.Code == m.ActualLocation);
                if (allocateCell == null)
                {
                    message = "仓位信息有误！";
                    return false;
                }
                pallobj.LocationCode = allocateCell.Code;
                pallobj.LocationName = allocateCell.Name;
                _palletRepository.UpdEntity(pallobj);
                //保存库存
                Inventory inventory = new Inventory()
                {
                    WarehouseId = allocateCell.WhId,
                    WarehouseCode = allocateCell.WhCode,
                    WarehouseName = allocateCell.WhName,
                    AreaCode = allocateCell.AreaCode,
                    AreaName = allocateCell.AreaName,
                    AreaId = allocateCell.AreaId,
                    LocationId = allocateCell.Id,
                    LocationCode = allocateCell.Code,
                    LocationDepth = allocateCell.DepthIndex,
                    LocationName = allocateCell.Name,
                    Status = 3,
                    PalletBarcode = m.PalletCode,
                    ParentPalletBarcode = item.PalletBarcode,
                    RelatedOrderDetailId = reorderDetail.Id,
                    BillType = (int)reorderDetail.BillType.GetValueOrDefault(),
                    IsLock = true,
                    MaterialId = reorderDetail.MaterialId,
                    MaterialCode = reorderDetail.MaterialCode,
                    MaterialName = reorderDetail.MaterialName,
                    CustomerId = reorderDetail.CustomerId,
                    CustomerName = reorderDetail.CustomerName,
                    SupplierId = reorderDetail.SupplierId,
                    SupplierName = reorderDetail.SupplierName,
                    HasSkuDetail = true,
                    PutawayQty = reorderDetail.Qty,
                    UnitId = reorderDetail.UnitId,
                    UnitName = reorderDetail.UnitName,
                    MaterialKeyId = reorderDetail.MaterialKeyId,
                    BatchNo = reorderDetail.BatchNo,
                    ExpireDate = reorderDetail.ExpireDate,
                    ProductDate = reorderDetail.ProductDate,
                    MaterialTypeCode = reorderDetail.MaterialTypeCode,
                    MaterialTypeName = reorderDetail.MaterialTypeName,
                    PickedQty = 0,
                    ErplocationCode = allocateCell.Erpcode,
                    RoutewayId = allocateCell.RoutewayId,
                    StackingStorageId = stackingStorageId,
                    LocationHeightType = allocateCell.HeightType,
                    LogicalPartCode = reorderDetail.LogicalPartCode,//按单据来
                    LocationColumnNo = allocateCell.ColumnNo,
                    LocationLayerNo = allocateCell.LayerNo,
                    LocationDistanceValue = allocateCell.DistanceValue,
                    LocationLineNo = allocateCell.LineNo,
                    AvailableQty = reorderDetail.ReceivedQty,
                    AllocateQty = 0,
                    CreateUserId = m.NowUserId,
                    CreateUserName = m.NowUserName,
                    PurOrderLineType = reorderDetail.Remark == "是" ? 1 : null
                };
                _inventoryRepository.AddEntity(inventory);
                if (!_unitOfWork.SaveChangesEntity())
                {
                    message = "保存库存失败！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                //库存明细保存
                InventoryDetail inventoryDetail = new InventoryDetail()
                {
                    Id = YitIdHelper.NextId(),
                    InventoryId = inventory.Id,
                    PalletBarcode = m.PalletCode,
                    SkuNum = reorderDetail.Qty,
                    IsSku = false,
                };
                _inventoryDetailRepository.AddEntity(inventoryDetail);
                //保存上架单主表
                string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string putawayCode = "PUT" + str;
                PutawayOrder putawayOrder = new PutawayOrder();
                putawayOrder.Id = YitIdHelper.NextId();
                putawayOrder.Code = putawayCode;
                putawayOrder.BillType = 1;
                putawayOrder.CreateDate = DateTime.Now;
                putawayOrder.RelatedOrderDetailId = reorderDetail.Id;
                putawayOrder.StackingStorageId = (long)stackingStorageId;
                putawayOrder.PalletBarcode = m.PalletCode;
                putawayOrder.LocationCode = allocateCell.Code;
                putawayOrder.LocationDepth = allocateCell.DepthIndex == 0 ? null : allocateCell.DepthIndex;
                putawayOrder.Status = 4;
                putawayOrder.Qty = reorderDetail.ReceivedQty;
                putawayOrder.MaterialId = reorderDetail.MaterialId;
                putawayOrder.MaterialCode = reorderDetail.MaterialCode;
                putawayOrder.MaterialName = reorderDetail.MaterialName;
                putawayOrder.MaterialKeyId = reorderDetail.MaterialKeyId;
                putawayOrder.SourceType = 1;
                putawayOrder.Roadway = allocateCell.RoutewayId.ToString();
                putawayOrder.CreateUserName = m.NowUserName;

                _putawayOrderRepository.AddEntity(putawayOrder);


                //上架单明细表保存
                PutawayOrderDetail putawayOrderDetail = new PutawayOrderDetail()
                {
                    Id = YitIdHelper.NextId(),
                    PutawayOrderId = putawayOrder.Id,
                    PalletBarcode = m.PalletCode,
                };
                _putawayOrderDetailRepository.AddEntity(putawayOrderDetail);
                result = _unitOfWork.SaveChangesEntity();
            }
            if (result)
            {
                return true;
            }
            _unitOfWork.RollbackChanges();
            return false;

        }
        public StackingReceivingsDto? GetReceivingRoderData(string PalletCode, out string message)
        {
            message = string.Empty;
            var stackingStoragelist = _stackingStorageRepository.GetEntityWhereAll(s => s.Status == 1 && s.PalletBarcode == PalletCode);

            if (!stackingStoragelist.Any())
            {
                message = "无组垛信息！";
                return null;
            }
            var invobj = _inventoryRepository.QueryIsEntityWhere(x => x.PalletBarcode == PalletCode);
            if (invobj != null)
            {
                message = "该托盘正在作业中";
                return null;
            }
            StackingReceivingsDto srmodel = new StackingReceivingsDto();
            srmodel.PallteCode = PalletCode;
            foreach (var item in stackingStoragelist)
            {
                if (item.RelatedOrderDetailId == null)
                {
                    message = "组垛入库关联id有误！";
                    return null;
                }
                srmodel.Cell = item.ExpectedLocation;

                MaterNum maternum = new MaterNum();
                maternum.MaterialCode = item.MaterialCode;
                maternum.Num = item.Qty;
                srmodel.materNum.Add(maternum);
            }

            //var orderDetail = _receivingOrderDetailRepository.QueryEntityById((long)stackingStorageobj.RelatedOrderDetailId);
            //if (orderDetail == null)
            //{
            //    message = "入库单查询失败";
            //    return null;
            //}


            return srmodel;
        }
        public bool FinishReceivingOrderDetail(string putcode, out string message)
        {
            _unitOfWork.BeginTransaction();
            try
            {
                bool result = StaticFinishReceivingOrderDetail(putcode, out message);
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }
        #endregion



        /// <summary>
        /// 完成入库
        /// </summary>
        /// <param name="putcode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool StaticFinishReceivingOrderDetail(string putcode, out string message)
        {
            message = string.Empty;
            var putobj = _putawayOrderRepository.QueryEntityWhere(x => x.Code == putcode && x.SourceType == 1 && x.Status == 4);
            if (putobj == null)
            {
                message = "找不到上架单！";
                return false;
            }
            string? pallbarcode = putobj.PalletBarcode;
            if (string.IsNullOrEmpty(pallbarcode))
            {
                message = "托盘信息有误！";
                return false;
            }
            var instructlist = _instructRepository.GetEntityWhereAll(x => x.PalletBarcode == pallbarcode && x.Status == 2 && x.InstructType == 1).ToList();
            if (!instructlist.Any())
            {
                message = "未查询到指令！";
                _unitOfWork.RollbackChanges();
                return false;
            }
            foreach (var instruct in instructlist)
            {
                if (string.IsNullOrEmpty(instruct.PalletBarcode))
                {
                    message = "参数错误";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (instruct.RelatedOrderId == null)
                {
                    message = "关联的入库单id信息有误！";
                    return false;
                }
                var orderDetail = _receivingOrderDetailRepository.QueryEntityById((long)instruct.RelatedOrderId);
                if (orderDetail == null)
                {
                    message = "入库单明细不存在";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                var inventory = _inventoryRepository.QueryEntityWhere(x => x.PalletBarcode == instruct.PalletBarcode && x.IsLock == true && x.RelatedOrderDetailId == (long)instruct.RelatedOrderId);
                if (inventory == null)
                {
                    message = "库存数据不存在";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                var cell = _cellRepository.QueryEntityWhere(x => x.Code == instruct.ExpectedToLocation);
                if (cell == null)
                {
                    message = "仓位数据不存在";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                DateTime? now = DateTime.Now;
                instruct.Status = 4;
                instruct.EndTime = now;
                _instructRepository.UpdEntity(instruct);
                inventory.Status = 1;
                inventory.AllocateQty = 0;
                inventory.InStockDate = now;
                inventory.PutawayQty = instruct.Qty;
                inventory.IsLock = false;
                _inventoryRepository.UpdEntity(inventory);
                orderDetail.ReceivedQty = instruct.Qty;
                orderDetail.InStarDate = now;
                orderDetail.Status = 3;
                _receivingOrderDetailRepository.UpdEntity(orderDetail);
                //删除组垛信息
                var stackingstorage = _stackingStorageRepository.QueryEntityById((long)instruct.StackingStorageId);
                if (stackingstorage != null)
                    _stackingStorageRepository.DelEntity(stackingstorage);

                //库存流水
                InventoryLog inventoryLog = new InventoryLog()
                {
                    Id = YitIdHelper.NextId(),
                    SourceType = 0,
                    SourceSn = orderDetail.OrderSn,
                    WarehouseId = orderDetail.WarehouseId,
                    WarehouseName = orderDetail.WarehouseName,
                    AreaName = inventory.AreaName,
                    AreaId = inventory.AreaId,
                    LocationCode = inventory.LocationCode,
                    PalletBarcode = instruct.PalletBarcode,
                    MaterialId = orderDetail.MaterialId,
                    MaterialCode = orderDetail.MaterialCode,
                    MaterialName = orderDetail.MaterialName,
                    BatchNo = orderDetail.BatchNo,
                    StartQty = 0,
                    ChangeQty = instruct.Qty,
                    EndQty = instruct.Qty,
                    BaseUnitId = orderDetail.UnitId,
                    BaseUnitName = orderDetail.UnitName,
                    CreateDate = DateTime.Now,
                };
                _inventoryLogRepository.AddEntity(inventoryLog);
            }
            var putlist = _putawayOrderRepository.GetEntityWhereAll(x => x.SourceType == 1 && x.Status == 4 && x.PalletBarcode == pallbarcode);
            foreach (var item in putlist)
            {
                item.Status = 5;
                item.Fifodate = DateTime.Now;
                _putawayOrderRepository.UpdEntity(item);
            }

            return _unitOfWork.SaveChangesEntity();

        }

        public PickReceivingsDto? GetPickReceivingsInventoryDto(string palletCode, out string message)
        {
            message = string.Empty;
            var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == palletCode);
            if (pallobj == null || pallobj.Status == 0)
            {
                message = "托盘不存在或已被禁用！";
                return null;
            }
            var invlist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == palletCode && x.Status == 1 && x.IsLock == false || (x.PalletBarcode == palletCode && x.Status == 4 && x.IsLock == false));
            PickReceivingsDto pickReceivingsDto = new PickReceivingsDto();
            pickReceivingsDto.PallteCode = palletCode;
            pickReceivingsDto.LoadFactor = pallobj.LoadFactor;
            foreach (var item in invlist)
            {
                pickReceivingsDto.Cell = item.LocationCode;
                PickMaterNum pickmaternum = new PickMaterNum();
                pickmaternum.MaterialCode = item.MaterialCode;
                pickmaternum.MaterialName = item.MaterialName;
                pickmaternum.Batch = item.BatchNo;
                pickmaternum.Arecode = item.AreaCode;
                pickmaternum.InventoryId = item.Id;
                pickmaternum.Num = item.AvailableQty;
                pickReceivingsDto.pickMaterNum.Add(pickmaternum);
            }
            return pickReceivingsDto;
        }

        public bool StartPickReceivingOrderDetail(PickReceivingsDto m, out string message)
        {
            message = string.Empty;
            decimal? startqty = 0;
            bool result = false;
            var ilist = _inventoryRepository.GetEntityAlls();
            var mlist = _materialRepository.GetEntityAlls();
            var rblist = _receivingBillRepository.GetEntityAlls();
            var rbdlist = _receivingBillDetailRepository.GetEntityAlls();
            var rlist = _receivingOrderDetailRepository.GetEntityAlls();
            var clist = _cellRepository.GetEntityAlls();
            try
            {
                _unitOfWork.BeginTransaction();
                var pobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == m.PallteCode);
                if (pobj == null)
                {
                    message = "托盘不存在！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (pobj.Status == 0)
                {
                    message = "托盘已被禁用！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                pobj.LoadFactor = m.LoadFactor;
                _palletRepository.UpdEntity(pobj);
                //新增物料
                if (m.IsAdd)
                {
                    //库存中已有物料增加数量
                    foreach (var item in m.pickMaterNum)
                    {
                        if (item.Qty <= 0 || item.Qty == null)
                        {
                            message = "数量有误！";
                            _unitOfWork.RollbackChanges();
                            result = false;
                        }
                        //添加入库单
                        var rbdobj = rbdlist.FirstOrDefault(x => x.BillNo == m.BillNo && x.ReceivedQty + item.Qty <= x.Qty);
                        if (rbdobj == null)
                        {
                            message = "收货单明细有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        var rbobj = rblist.FirstOrDefault(x => x.Id == rbdobj.BillId);
                        if (rbobj == null)
                        {
                            message = "收货单有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbobj.Status == 2)
                        {
                            message = "收货单已完成";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty > rbobj.TotalQty)
                        {
                            message = "已收货数量不能大于总数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty == rbobj.TotalQty)
                        {
                            rbobj.Status = 2;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        else
                        {
                            rbobj.Status = 1;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        var mobj = mlist.FirstOrDefault(x => x.Id == (long)rbdobj.MaterialId);
                        if (mobj == null)
                        {
                            message = "物料信息有误！";
                            return false;
                        }
                        var maxqty = mobj.MaxSafetyStock;
                        var cobj = clist.FirstOrDefault(x => x.Code == m.Cell);
                        if (cobj == null)
                        {
                            message = "找不到仓位信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
                        receivingOrder.OrderSn = m.BillNo;
                        //本地入库
                        receivingOrder.BillType = rbobj.BillType;
                        receivingOrder.WarehouseId = rbobj.WarehouseId;
                        receivingOrder.WarehouseCode = rbobj.WarehouseCode;
                        receivingOrder.WarehouseName = rbobj.WarehouseName;
                        receivingOrder.AreaCode = cobj.AreaCode;
                        receivingOrder.AreaName = cobj.AreaName;
                        receivingOrder.SupplierId = rbobj.SupplierId;
                        receivingOrder.SupplierName = rbobj.SupplierName;
                        receivingOrder.CustomerId = rbobj.CustomerId;
                        receivingOrder.CustomerName = rbobj.CustomerName;
                        receivingOrder.MaterialId = rbdobj.MaterialId;
                        receivingOrder.MaterialCode = rbdobj.MaterialCode;
                        receivingOrder.MaterialName = rbdobj.MaterialName;
                        receivingOrder.MaterialTypeCode = rbdobj.MaterialTypeCode;
                        receivingOrder.MaterialTypeName = rbdobj.MaterialTypeName;
                        receivingOrder.UnitId = mobj.UnitId;
                        receivingOrder.UnitName = mobj.UnitName;
                        receivingOrder.BatchNo = rbdobj.BatchNo;
                        //订单来源默认手动创建
                        receivingOrder.SourceType = 2;
                        //质检状态默认为合格
                        receivingOrder.QualityState = 1;
                        //质量状态
                        receivingOrder.Status = 3;
                        receivingOrder.ReceivedQty = item.Qty;
                        receivingOrder.PackagedQty = 0;
                        receivingOrder.PackQty = 0;
                        receivingOrder.BatchNoExplain = rbdobj.BatchNoExplain;
                        receivingOrder.OutFactoryDate = rbdobj.OutFactoryDate;
                        receivingOrder.ProduceFactory = rbdobj.ProduceFactory;
                        receivingOrder.ProductDate = rbdobj.ProductDate;
                        receivingOrder.ExpireDate = rbdobj.ExpireDate;
                        receivingOrder.Qty = item.Qty;
                        receivingOrder.PalletBarcode = m.PallteCode;
                        receivingOrder.ReceivingBillDetailId = rbdobj.Id;
                        receivingOrder.ReceivingBillId = rbobj.Id;
                        #region 审计字段
                        receivingOrder.CreateUserId = m.NowUserId;
                        receivingOrder.CreateUserName = m.NowUserName;
                        #endregion
                        //采购订单行项目类型
                        receivingOrder.PurOrderLineType = 0;
                        receivingOrder.StackedQty = item.Qty;
                        receivingOrder.LocationId = cobj.Id;
                        receivingOrder.LocationCode = cobj.Code;
                        receivingOrder.LocationName = cobj.Name;
                        _receivingOrderDetailRepository.AddEntity(receivingOrder);
                        if (_unitOfWork.SaveChangesEntity() == false)
                        {
                            message = "添加入库单失败!";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #region 增加库存
                        Inventory inventory = new Inventory();
                        inventory.WarehouseId = cobj.WhId;
                        inventory.WarehouseCode = cobj.WhCode;
                        inventory.WarehouseName = cobj.WhName;
                        inventory.AreaCode = cobj.AreaCode;
                        inventory.AreaName = cobj.AreaName;
                        inventory.AreaId = cobj.AreaId;
                        inventory.LocationId = cobj.Id;
                        inventory.LocationCode = cobj.Code;
                        inventory.LocationDepth = cobj.DepthIndex;
                        inventory.LocationName = cobj.Name;
                        if (inventory.AreaCode == "2")
                            inventory.Status = 4;
                        else
                            inventory.Status = 1;
                        inventory.PalletBarcode = m.PallteCode;
                        inventory.ParentPalletBarcode = m.PallteCode;
                        inventory.RelatedOrderDetailId = receivingOrder.Id;
                        inventory.BillType = (int)receivingOrder.BillType.GetValueOrDefault();
                        inventory.IsLock = false;
                        inventory.MaterialId = receivingOrder.MaterialId;
                        inventory.MaterialCode = receivingOrder.MaterialCode;
                        inventory.MaterialName = receivingOrder.MaterialName;
                        inventory.CustomerId = receivingOrder.CustomerId;
                        inventory.CustomerName = receivingOrder.CustomerName;
                        inventory.SupplierId = receivingOrder.SupplierId;
                        inventory.SupplierName = receivingOrder.SupplierName;
                        inventory.HasSkuDetail = true;
                        inventory.PutawayQty = receivingOrder.Qty;
                        inventory.UnitId = receivingOrder.UnitId;
                        inventory.UnitName = receivingOrder.UnitName;
                        inventory.MaterialKeyId = receivingOrder.MaterialKeyId;
                        inventory.BatchNo = receivingOrder.BatchNo;
                        inventory.ExpireDate = receivingOrder.ExpireDate;
                        inventory.ProductDate = receivingOrder.ProductDate;
                        inventory.MaterialTypeCode = receivingOrder.MaterialTypeCode;
                        inventory.MaterialTypeName = receivingOrder.MaterialTypeName;
                        inventory.PickedQty = 0;
                        inventory.ErplocationCode = cobj.Erpcode;
                        inventory.RoutewayId = cobj.RoutewayId;
                        inventory.StackingStorageId = 0;
                        inventory.LocationHeightType = cobj.HeightType;
                        inventory.LogicalPartCode = receivingOrder.LogicalPartCode;//按单据来
                        inventory.LocationColumnNo = cobj.ColumnNo;
                        inventory.LocationLayerNo = cobj.LayerNo;
                        inventory.LocationDistanceValue = cobj.DistanceValue;
                        inventory.LocationLineNo = cobj.LineNo;
                        inventory.AvailableQty = receivingOrder.ReceivedQty;
                        inventory.AllocateQty = 0;
                        inventory.CreateUserId = m.NowUserId;
                        inventory.CreateUserName = m.NowUserName;
                        _inventoryRepository.AddEntity(inventory);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存库存失败！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        //库存明细保存
                        InventoryDetail inventoryDetail = new InventoryDetail()
                        {
                            Id = YitIdHelper.NextId(),
                            InventoryId = inventory.Id,
                            PalletBarcode = m.PallteCode,
                            SkuNum = receivingOrder.Qty,
                            IsSku = false,
                        };
                        _inventoryDetailRepository.AddEntity(inventoryDetail);
                        #endregion
                        if (inventory.AvailableQty > maxqty)
                        {
                            message = "调增后的库存大于该物料最大库存预警！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        startqty = inventory.AvailableQty;
                        //添加指令
                        Instruct instruct = new Instruct
                        {
                            Status = 4,
                            WarehouseCode = inventory.WarehouseCode,
                            ToLocation = inventory.LocationCode,
                            WorkDeviceType = 1,
                            InstructType = 6,
                            Action = 0,
                            RelatedOrderId = inventory.RelatedOrderDetailId,
                            DeviceCode = "",
                            ExpectedToLocation = inventory.LocationCode,
                            InstructIndex = 1,
                            PalletBarcode = inventory.PalletBarcode,
                            Priority = 9999,
                            Qty = (decimal)inventory.AvailableQty,
                            BusinessType = (int)EmBusinessType.In,
                            EndTime = DateTime.Now,
                            ScanedBarcode = inventory.PalletBarcode
                        };
                        _instructRepository.AddEntity(instruct);
                        //保存上架单主表
                        string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string putawayCode = "RRT" + str;
                        PutawayOrder putawayOrder = new PutawayOrder();
                        putawayOrder.Id = YitIdHelper.NextId();
                        putawayOrder.Code = putawayCode;
                        putawayOrder.BillType = 1;
                        putawayOrder.RelatedOrderDetailId = inventory.Id;
                        putawayOrder.PalletBarcode = inventory.PalletBarcode;
                        putawayOrder.LocationCode = inventory.LocationCode;
                        putawayOrder.LocationDepth = inventory.LocationDepth == 0 ? null : inventory.LocationDepth;
                        putawayOrder.Status = 5;
                        putawayOrder.Qty = inventory.AvailableQty;
                        putawayOrder.MaterialId = inventory.MaterialId;
                        putawayOrder.MaterialCode = inventory.MaterialCode;
                        putawayOrder.MaterialName = inventory.MaterialName;
                        putawayOrder.MaterialKeyId = inventory.MaterialKeyId;
                        putawayOrder.SourceType = 1;
                        putawayOrder.Roadway = inventory.RoutewayId.ToString();

                        _putawayOrderRepository.AddEntity(putawayOrder);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存库存失败！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        //上架单明细表保存
                        PutawayOrderDetail putawayOrderDetail = new PutawayOrderDetail()
                        {
                            Id = YitIdHelper.NextId(),
                            PutawayOrderId = putawayOrder.Id,
                            PalletBarcode = inventory.PalletBarcode,
                        };
                        _putawayOrderDetailRepository.AddEntity(putawayOrderDetail);
                        //库存流水
                        InventoryLog inventoryLog = new InventoryLog()
                        {
                            Id = YitIdHelper.NextId(),
                            SourceType = 0,
                            SourceSn = receivingOrder.OrderSn,
                            WarehouseId = receivingOrder.WarehouseId,
                            WarehouseName = receivingOrder.WarehouseName,
                            AreaName = inventory.AreaName,
                            AreaId = inventory.AreaId,
                            LocationCode = inventory.LocationCode,
                            PalletBarcode = inventory.PalletBarcode,
                            MaterialId = receivingOrder.MaterialId,
                            MaterialCode = receivingOrder.MaterialCode,
                            MaterialName = receivingOrder.MaterialName,
                            BatchNo = receivingOrder.BatchNo,
                            StartQty = 0,
                            ChangeQty = item.Qty,
                            EndQty = inventory.AvailableQty,
                            BaseUnitId = receivingOrder.UnitId,
                            BaseUnitName = receivingOrder.UnitName,
                            CreateDate = DateTime.Now,
                            Remark = "拣选入库加新物料"
                        };
                        _inventoryLogRepository.AddEntity(inventoryLog);
                    }
                }
                else
                {
                    //库存中已有物料增加数量
                    foreach (var item in m.pickMaterNum)
                    {
                        if (item.Qty <= 0 || item.Qty == null)
                        {
                            message = "数量有误！";
                            result = true;
                        }
                        //添加入库单
                        var rbdobj = rbdlist.FirstOrDefault(x => x.BillNo == m.BillNo && x.BatchNo == m.pickMaterNum.First().Batch && x.MaterialCode == m.pickMaterNum.First().MaterialCode);
                        if (rbdobj == null)
                        {
                            message = "收货单明细有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        var rbobj = rblist.FirstOrDefault(x => x.Id == rbdobj.BillId);
                        if (rbobj == null)
                        {
                            message = "收货单有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbobj.Status == 2)
                        {
                            message = "收货单已完成";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty > rbobj.TotalQty)
                        {
                            message = "已收货数量不能大于总数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty == rbobj.TotalQty)
                        {
                            rbobj.Status = 2;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        else
                        {
                            rbobj.Status = 1;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        var mobj = mlist.FirstOrDefault(x => x.Id == (long)rbdobj.MaterialId);
                        if (mobj == null)
                        {
                            message = "物料信息有误！";
                            return false;
                        }
                        var maxqty = mobj.MaxSafetyStock;
                        var cobj = clist.FirstOrDefault(x => x.Code == m.Cell);
                        if (cobj == null)
                        {
                            message = "找不到仓位信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
                        receivingOrder.OrderSn = m.BillNo;
                        //本地入库
                        receivingOrder.BillType = rbobj.BillType;
                        receivingOrder.WarehouseId = rbobj.WarehouseId;
                        receivingOrder.WarehouseCode = rbobj.WarehouseCode;
                        receivingOrder.WarehouseName = rbobj.WarehouseName;
                        receivingOrder.AreaCode = cobj.AreaCode;
                        receivingOrder.AreaName = cobj.AreaName;
                        receivingOrder.SupplierId = rbobj.SupplierId;
                        receivingOrder.SupplierName = rbobj.SupplierName;
                        receivingOrder.CustomerId = rbobj.CustomerId;
                        receivingOrder.CustomerName = rbobj.CustomerName;
                        receivingOrder.MaterialId = rbdobj.MaterialId;
                        receivingOrder.MaterialCode = rbdobj.MaterialCode;
                        receivingOrder.MaterialName = rbdobj.MaterialName;
                        receivingOrder.MaterialTypeCode = rbdobj.MaterialTypeCode;
                        receivingOrder.MaterialTypeName = rbdobj.MaterialTypeName;
                        receivingOrder.UnitId = mobj.UnitId;
                        receivingOrder.UnitName = mobj.UnitName;
                        receivingOrder.BatchNo = rbdobj.BatchNo;
                        //订单来源默认手动创建
                        receivingOrder.SourceType = 2;
                        //质检状态默认为合格
                        receivingOrder.QualityState = 1;
                        //质量状态
                        receivingOrder.Status = 3;
                        receivingOrder.ReceivedQty = item.Qty;
                        receivingOrder.PackagedQty = 0;
                        receivingOrder.PackQty = 0;
                        receivingOrder.BatchNoExplain = rbdobj.BatchNoExplain;
                        receivingOrder.OutFactoryDate = rbdobj.OutFactoryDate;
                        receivingOrder.ProduceFactory = rbdobj.ProduceFactory;
                        receivingOrder.ProductDate = rbdobj.ProductDate;
                        receivingOrder.ExpireDate = rbdobj.ExpireDate;
                        receivingOrder.Qty = item.Qty;
                        receivingOrder.PalletBarcode = m.PallteCode;
                        receivingOrder.ReceivingBillDetailId = rbdobj.Id;
                        receivingOrder.ReceivingBillId = rbobj.Id;
                        #region 审计字段
                        receivingOrder.CreateUserId = m.NowUserId;
                        receivingOrder.CreateUserName = m.NowUserName;
                        #endregion
                        //采购订单行项目类型
                        receivingOrder.PurOrderLineType = 0;
                        receivingOrder.StackedQty = item.Qty;
                        receivingOrder.LocationId = cobj.Id;
                        receivingOrder.LocationCode = cobj.Code;
                        receivingOrder.LocationName = cobj.Name;
                        _receivingOrderDetailRepository.AddEntity(receivingOrder);
                        if (_unitOfWork.SaveChangesEntity() == false)
                        {
                            message = "添加入库单失败!";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        var invobj = ilist.FirstOrDefault(x => x.Id == item.InventoryId);
                        if (invobj == null)
                        {
                            message = "找不到库存信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (invobj.AvailableQty + item.Qty > maxqty)
                        {
                            message = "调增后的库存大于该物料最大库存预警！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        startqty = invobj.AvailableQty;
                        invobj.AvailableQty += item.Qty;
                        _inventoryRepository.UpdEntity(invobj);
                        //出库单单子明细
                        var sllist = _shippingLockCellRepository.GetEntityWhereAll(x => x.InventoryId == invobj.Id && x.Status != 4);
                        foreach (var item2 in sllist)
                        {
                            item2.InventoryQty = invobj.AvailableQty;
                        }
                        //库存流水
                        InventoryLog inventoryLog = new InventoryLog()
                        {
                            Id = YitIdHelper.NextId(),
                            SourceType = 0,
                            SourceSn = receivingOrder.OrderSn,
                            WarehouseId = receivingOrder.WarehouseId,
                            WarehouseName = receivingOrder.WarehouseName,
                            AreaName = invobj.AreaName,
                            AreaId = invobj.AreaId,
                            LocationCode = invobj.LocationCode,
                            PalletBarcode = invobj.PalletBarcode,
                            MaterialId = receivingOrder.MaterialId,
                            MaterialCode = receivingOrder.MaterialCode,
                            MaterialName = receivingOrder.MaterialName,
                            BatchNo = receivingOrder.BatchNo,
                            StartQty = startqty,
                            ChangeQty = item.Qty,
                            EndQty = invobj.AvailableQty,
                            BaseUnitId = receivingOrder.UnitId,
                            BaseUnitName = receivingOrder.UnitName,
                            CreateDate = DateTime.Now,
                            Remark = "拣选入库加数量"
                        };
                        _inventoryLogRepository.AddEntity(inventoryLog);
                        #region 弃用
                        //if (item.Arecode == "1")
                        //    result = StaticFinishPickReceivingOrderDetail(putawayOrder.Code,out message);
                        #endregion
                    }
                }
                result = _unitOfWork.SaveChangesEntity();
                if (result)
                {
                    message = "操作成功！";
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }

        #region 组垛私有方法
        /// <summary>
        /// 添加入库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="palletBarcode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDetail(ReceivingBillDetail m, decimal receivedQty, long nowuserid, string nowusername, string palletBarcode, out string message)
        {
            message = string.Empty;
            if (m.ReceivedQty < 0 || string.IsNullOrEmpty(palletBarcode))
            {
                message = "收货数量或托盘有误";
                _unitOfWork.RollbackChanges();
                return false;
            }
            var reobj = _receivingBillRepository.QueryEntityById(m.BillId);
            if (reobj == null)
            {
                message = "收货单有误";
                _unitOfWork.RollbackChanges();
                return false;
            }
            var mobj = _materialRepository.QueryEntityById(m.MaterialId);
            if (mobj == null)
            {
                message = "物料信息有误！";
                _unitOfWork.RollbackChanges();
                return false;
            }
            //var aobj = _areaRepository.QueryEntityById(m.AreaId);
            //if (aobj == null && m.StoLocation == null)
            //{
            //    message = "库区信息有误！";
            //    _unitOfWork.RollbackChanges();
            //    return false;
            //}
            ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
            receivingOrder.OrderSn = m.BillNo;
            //本地入库
            receivingOrder.BillType = reobj.BillType;
            //if(aobj!=null)
            //    receivingOrder.AreaCode = aobj.Code;
            receivingOrder.SupplierId = reobj.SupplierId;
            receivingOrder.SupplierName = reobj.SupplierName;
            receivingOrder.CustomerId = reobj.CustomerId;
            receivingOrder.CustomerName = reobj.CustomerName;
            receivingOrder.MaterialId = m.MaterialId;
            receivingOrder.MaterialCode = m.MaterialCode;
            receivingOrder.MaterialName = m.MaterialName;
            receivingOrder.MaterialTypeCode = m.MaterialTypeCode;
            receivingOrder.MaterialTypeName = m.MaterialTypeName;
            receivingOrder.UnitId = mobj.UnitId;
            receivingOrder.UnitName = mobj.UnitName;
            receivingOrder.BatchNo = m.BatchNo;
            //订单来源默认手动创建
            receivingOrder.SourceType = 2;
            //质检状态默认为合格
            receivingOrder.QualityState = 1;
            //质量状态
            receivingOrder.Status = 0;
            receivingOrder.ReceivedQty = receivedQty;
            receivingOrder.PackagedQty = 0;
            receivingOrder.PackQty = 0;
            receivingOrder.BatchNoExplain = m.BatchNoExplain;
            receivingOrder.OutFactoryDate = m.OutFactoryDate;
            receivingOrder.ProduceFactory = m.ProduceFactory;
            receivingOrder.ProductDate = m.ProductDate;
            receivingOrder.ExpireDate = m.ExpireDate;
            receivingOrder.Qty = receivedQty;
            receivingOrder.PalletBarcode = palletBarcode;
            receivingOrder.ReceivingBillDetailId = m.Id;
            receivingOrder.ReceivingBillId = reobj.Id;
            #region 审计字段
            receivingOrder.CreateUserId = nowuserid;
            receivingOrder.CreateUserName = nowusername;
            #endregion
            //采购订单行项目类型
            receivingOrder.PurOrderLineType = 0;
            receivingOrder.StackedQty = receivedQty;
            receivingOrder.Layer = m.Layer;
            if (!string.IsNullOrEmpty(m.StoLocation))
                receivingOrder.LocationCode = m.StoLocation;
            receivingOrder.Remark = m.IsPick ? "是" : "否";
            _receivingOrderDetailRepository.AddEntity(receivingOrder);
            if (_unitOfWork.SaveChangesEntity() == false)
            {
                message = "添加入库单失败!";
                _unitOfWork.RollbackChanges();
                return false;
            }
            return AddReceivingOrderDetailStackingStorage(receivingOrder, out message);
        }

        /// <summary>
        /// 添加组垛
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDetailStackingStorage(ReceivingOrderDetail m, out string message)
        {
            message = string.Empty;

            //查看站台模式，必须为入库才可以 A01为固定值
            var stationobj = _stationRepository.QueryEntityWhere(s => s.Code == "A01");
            if (stationobj is null)
            {
                message = "未查询到入库口信息！";
                return false;
            }
            if (stationobj.FunctionType != 1)
            {
                message = "当前模式不是入库!";
                return false;
            }
            //var stationobj = _stationRepository.GetEntityWhereAll(s=>s.);
            //if (!stationobj.Any())
            //{
            //    message = "请配置站台!";
            //    return false;
            //}
            //手动选择仓位后这里是不等于空的
            if (!string.IsNullOrEmpty(m.LocationCode))
            {
                //锁仓位
                var cells = _cellRepository.QueryEntityWhere(x => x.Code == m.LocationCode);
                if (cells == null)
                {
                    message = "找不到匹配仓位!";
                    return false;
                }
                if (cells.FullStatus == 1 || cells.Status != 1 || cells.BusinessType != 0 || cells.IsLock == true)
                {
                    message = "已选择的仓位状态已被占用或异常!";
                    return false;
                }
                cells.BusinessType = 1;
                cells.IsLock = true;
                cells.FullStatus = 1;
                _cellRepository.UpdEntity(cells);
                StackingStorage stackingStorages = new StackingStorage();
                stackingStorages.WarehouseName = m.WarehouseName;
                stackingStorages.WarehouseCode = m.WarehouseCode;
                stackingStorages.BillType = 1;
                stackingStorages.RelatedOrderDetailId = m.Id;
                stackingStorages.Status = 1;
                stackingStorages.PalletBarcode = m.PalletBarcode;
                stackingStorages.Qty = m.Qty;
                stackingStorages.PackQty = 1;
                stackingStorages.MaterialId = m.MaterialId;
                stackingStorages.MaterialCode = m.MaterialCode;
                stackingStorages.MaterialName = m.MaterialName;
                stackingStorages.MaterialKeyId = m.MaterialKeyId;
                stackingStorages.BatchNo = m.BatchNo;
                stackingStorages.Fifodate = DateTime.Now;
                stackingStorages.ExpectedLocation = m.LocationCode;
                _stackingStorageRepository.AddEntity(stackingStorages);
                //更新入库单状态
                m.WarehouseId = cells.WhId;
                m.WarehouseCode = cells.WhCode;
                m.WarehouseName = cells.WhName;
                m.AreaCode = cells.AreaCode;
                m.AreaName = cells.AreaName;
                m.LocationId = cells.Id;
                m.LocationName = cells.Name;
                m.LocationCode = cells.Code;
                _receivingOrderDetailRepository.UpdEntity(m);
                message = m.LocationCode;
                return _unitOfWork.SaveChangesEntity();
            }
            string cellcode = "";
            var stackobj = _stackingStorageRepository.QueryIsEntityWhere(x => x.PalletBarcode == m.PalletBarcode);
            if (stackobj != null)
                cellcode = stackobj.ExpectedLocation;

            StackingStorage stackingStorage = new StackingStorage();
            stackingStorage.WarehouseName = m.WarehouseName;
            stackingStorage.WarehouseCode = m.WarehouseCode;
            stackingStorage.BillType = 1;
            stackingStorage.RelatedOrderDetailId = m.Id;
            stackingStorage.Status = 1;
            stackingStorage.PalletBarcode = m.PalletBarcode;
            stackingStorage.Qty = m.Qty;
            stackingStorage.PackQty = 1;
            stackingStorage.MaterialId = m.MaterialId;
            stackingStorage.MaterialCode = m.MaterialCode;
            stackingStorage.MaterialName = m.MaterialName;
            stackingStorage.MaterialKeyId = m.MaterialKeyId;
            stackingStorage.BatchNo = m.BatchNo;
            stackingStorage.Fifodate = DateTime.Now;
            //组垛个物料第一次已经分配好仓位后直接用分配好的仓位
            if (!string.IsNullOrEmpty(cellcode))
            {
                stackingStorage.ExpectedLocation = cellcode;
                message = cellcode;
            }
            else
            {
                //获取一个新仓位
                if (!GetCellCode(m.AreaCode, m.Layer, out message))
                {
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                cellcode = message;
                stackingStorage.ExpectedLocation = cellcode;
            }
            _stackingStorageRepository.AddEntity(stackingStorage);
            //锁仓位
            var cell = _cellRepository.QueryEntityWhere(x => x.Code == cellcode);
            if (cell == null)
            {
                message = "找不到匹配仓位!";
                return false;
            }
            cell.BusinessType = 1;
            cell.IsLock = true;
            cell.FullStatus = 1;
            _cellRepository.UpdEntity(cell);

            //更新入库单状态
            m.WarehouseId = cell.WhId;
            m.WarehouseCode = cell.WhCode;
            m.WarehouseName = cell.WhName;
            m.AreaCode = cell.AreaCode;
            m.AreaName = cell.AreaName;
            m.LocationId = cell.Id;
            m.LocationName = cell.Name;
            m.LocationCode = cell.Code;
            _receivingOrderDetailRepository.UpdEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }
        /// <summary>
        /// 获取一个仓位
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool GetCellCode(string acode, EmLayer? layer, out string message)
        {
            message = string.Empty;
            //if (string.IsNullOrEmpty(acode))
            //{
            //    message = "库区编码有误！";
            //    return false;
            //}
            Cell? cellobj = new Cell();

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.Status == 1);
            if (routewayQuery == null)
            {
                message = "无可用巷道!";
                return false;
            }
            List<long> enabledRoutewayIds = routewayQuery.Select(t => t.Id).ToList();//只取巷道id
            // 获取所有货架
            var shelves = _shelfRepository.GetEntityWhereAll(x => x.Status == 1 && enabledRoutewayIds.Contains((long)x.RoutewayId));
            if (shelves == null)
            {
                message = "无可用货架!";
                return false;
            }
            List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
            //获取所有可用仓位
            var cellQuery = _cellRepository
                .GetEntityWhereAll(x => x.Status == 1
                                        && x.FullStatus == 0
                                        && x.IsLock == false
                                        && enabledRoutewayIds.Contains((long)x.RoutewayId)
                                        && enabledShelves.Contains((long)x.ShelfId)).ToList();
            if (layer.HasValue)//判断高中低位
            {
                cellQuery = cellQuery.Where(s => s.LayerNo == (int)layer).ToList();
            }
            if (cellQuery.Count <= 8 || !cellQuery.Any()) //至少流出8个货位因为极端情况下可能会出现一次移库4个托盘或更多
            {
                message = "无可用仓位!";
                return false;
            }
            //var inventoryQuery = Context.TInventory.AsNoTracking(); //获取库存数据
            cellobj = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LayerNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LineNo)
                                .FirstOrDefault();
            if (cellobj != null)
            {

                message = cellobj.Code;
                return true;
            }
            cellobj = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                              .ThenBy(c => c.LayerNo)
                              .ThenBy(c => c.ColumnNo)
                              .ThenBy(c => c.LineNo)
                              .FirstOrDefault();
            if (cellobj != null)
            {
                message = cellobj.Code;
                return true;
            }

            message = "无可用仓位!";
            return false;
        }
        #endregion



        #region PC
        public List<ReceivingOrderDetail> GetReceivingOrderDetailList(DateTime? startTime, DateTime? endTime, string? orderSn, int status, int pageIndex, int pageSize, out int totalCount)
        {
            var list = _receivingOrderDetailRepository.GetEntityAlls();
            //入库单号
            if (!string.IsNullOrEmpty(orderSn))
            {
                list = list.Where(x => x.OrderSn.Contains(orderSn));
            }

            if (status < 8)
            {
                list = list.Where(x => x.Status == status);
            }

            if (startTime != null && endTime != null)
            {
                list = list.Where(s => s.CreateDate.Date >= startTime && s.CreateDate.Date <= endTime);
            }
            else if (endTime != null)
            {
                list = list.Where(s => s.CreateDate.Date <= endTime);
            }
            else if (startTime != null)
            {
                list = list.Where(s => s.CreateDate.Date >= startTime);
            }

            var lists = _receivingOrderDetailRepository.GetEntityAlls(list, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return lists.ToList();
        }
        #endregion   


        public bool EPCGetDataIn(EPCInputModel model, out string errormsg)
        {
            errormsg = "";
            var result = model.result;
            if (result == null || result.Count == 0)
            {
                errormsg = "参数错误";
                return false;
            }
            var epcs = result.Select(t => t.epc).ToList();
            //var materialList = _materialRepository.GetEntityWhereAll(t => epcs.Contains(t.Code)).ToList();
            //if (materialList == null || materialList.Count == 0)
            //{
            //    errormsg = "物料管理：未查找到装备信息";
            //    return false;
            //}
            var cell = _cellRepository.GetEntityAlls().Where(t => t.Status == 1 && t.FullStatus == 0 && t.IsLock == false && t.BusinessType == (int)EmBusinessType.None).OrderBy(t => t.LineNo).OrderBy(t => t.LayerNo).OrderBy(t => t.ColumnNo).FirstOrDefault();
            if (cell == null)
            {
                errormsg = "无可用仓位";
                return false;
            }
            List<Inventory> invtoryList = new List<Inventory>();
            bool res = false;
            _unitOfWork.BeginTransaction();
            try
            {
                foreach (var item in epcs)
                {
                    var invenItem = new Inventory
                    {
                        WarehouseId = cell.WhId,
                        WarehouseCode = cell.WhCode,
                        WarehouseName = cell.WhName,
                        AreaId = cell.AreaId,
                        AreaName = cell.AreaName,
                        AreaCode = cell.AreaCode,
                        LocationCode = cell.Code,
                        LocationName = cell.Name,
                        LocationLineNo = cell.LineNo,
                        LocationLayerNo = cell.LayerNo,
                        LocationColumnNo = cell.ColumnNo,
                        LocationId = cell.Id,
                        BusinessType = (int)EmBusinessType.In,
                        MaterialCode = item,
                        MaterialName = item,
                        AllocateQty = 1,
                        Status = 3,
                        IsLock = true,
                        PalletBarcode=""

                    };
                    _inventoryRepository.AddEntity(invenItem);
                    res = _unitOfWork.SaveChangesEntity();
                    if (!res)
                    {
                        errormsg = "添加失败";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }
                cell.ModifyDate = DateTime.Now;
                cell.FullStatus = 1;
                //cell.Status =2 ;
                cell.BusinessType = (int)EmBusinessType.In;
                cell.IsLock = true;
                _cellRepository.UpdEntity(cell);
                res = _unitOfWork.SaveChangesEntity();
                if (!res)
                {
                    errormsg = "添加失败";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                _unitOfWork.CommitChanges();
                return true;
            }
            catch (Exception ex)
            {
                errormsg = ex.Message;
                _unitOfWork.RollbackChanges();
                return false;
            }

        }


        public bool SubmitInventoryIn(string cellCode, out string errormsg)
        {
            errormsg = "";
            var cell = _cellRepository.QueryEntityWhere(t => t.Code == cellCode);
            if (cell == null)
            {
                errormsg = $"{cellCode}未查询到此仓位";
                return false;
            }
            if (cell.FullStatus == 0 || cell.IsLock == false)
            {
                errormsg = $"{cellCode}当前仓位状态有误";
                return false;
            }
            List<Inventory> invenListIn = _inventoryRepository.GetEntityWhereAll(t => t.LocationCode == cellCode && t.Status == 3).ToList();
            if (invenListIn == null || invenListIn.Count == 0)
            {
                errormsg = $"{cellCode}未查询到库存信息";
                return false;
            }
            bool result = false;
            _unitOfWork.BeginTransaction();
            try
            {
                cell.IsLock = false;
                cell.BusinessType = (int)EmBusinessType.None;
                cell.Status = 1;
                _cellRepository.UpdEntity(cell);
                result = _unitOfWork.SaveChangesEntity();
                if (!result)
                {
                    errormsg = "操作失败";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                foreach (var item in invenListIn)
                {
                    item.BusinessType = (int)EmBusinessType.None;
                    item.Status = 1;
                    item.AvailableQty = 1;
                    item.IsLock = false;
                    _inventoryRepository.UpdEntity(item);
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        errormsg = "操作失败";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }
                _unitOfWork.CommitChanges();
                return true;
            }
            catch (Exception ex)
            {
                _unitOfWork.RollbackChanges();
                errormsg = ex.Message;
                return false;
            }


        }


    }
}
